package com.demo.wechatweather.service;

import com.demo.wechatweather.VO.Forecast;
import com.demo.wechatweather.VO.Weather;
import com.demo.wechatweather.VO.WeatherResponse;
import com.demo.wechatweather.VO.Yesterday;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class WeatherDataServiceImpl implements WeatherDataService {
    private static final Logger LOGGER = LoggerFactory.getLogger(WeatherDataServiceImpl.class);

    private static final String WEATHER_URI = "http://wthrcdn.etouch.cn/weather_mini?";
    private static final long TIME_OUT = 1800L;
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public WeatherResponse getDataByCityId(String cityId) {
        String uri = WEATHER_URI + "cityKey=" + cityId;
        return this.doGetWeather(uri);
    }

    @Override
    public WeatherResponse getDataByCityName(String cityName) {
        String uri = WEATHER_URI + "city=" + cityName;
        return this.doGetWeather(uri);
    }

    @Override
    public void syncDateByCityId(String cityId) {
        String uri = WEATHER_URI + "city=" + cityId;
        this.saveWeatherDate(uri);

    }

    private void saveWeatherDate(String uri) {
        String key = uri;
        String strBody = null;
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        //ObjectMapper mapper = new ObjectMapper();
        //WeatherResponse resp = null;
        /*先查缓存,缓存中有的从缓存中取出
        if (stringRedisTemplate.hasKey(key))
        {
            LOGGER.info("Redis has data" + uri);
            strBody = ops.get(key);
        }else {
            LOGGER.info("Redis dose't has data" + uri); */
        //缓存中没有,再调服务接口来获取
        ResponseEntity<String> respString = restTemplate.getForEntity(uri, String.class);
        if (respString.getStatusCodeValue() == 200) {
            strBody = respString.getBody();
        }
        //数据写入缓存
        ops.set(key, strBody, TIME_OUT, TimeUnit.SECONDS);

    }

    private WeatherResponse doGetWeather(String uri) {
        String key = uri;
        String strBody = null;
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ObjectMapper mapper = new ObjectMapper();
        WeatherResponse resp = null;
        //先查缓存,缓存中有的从缓存中取出
        if (stringRedisTemplate.hasKey(key)) {
            LOGGER.info("Redis has data" + uri);
            strBody = ops.get(key);
        } else {
            LOGGER.info("Redis dose't has data" + uri);
            //缓存中没有,再调服务接口来获取
            ResponseEntity<String> respString = restTemplate.getForEntity(uri, String.class);
            if (respString.getStatusCodeValue() == 200) {
                strBody = respString.getBody();
            } else{
                return error();
            }

            //数据写入缓存
            LOGGER.info(strBody);
            ops.set(key, strBody, TIME_OUT, TimeUnit.SECONDS);
        }
        try {
            resp = mapper.readValue(strBody, WeatherResponse.class);
            if (resp.getStatus() > 1001){
                return error();
            }
        } catch (IOException e) {
            LOGGER.info("error" + e);
        }
        return resp;
    }

    public WeatherResponse error(){
        Yesterday yesterday = new Yesterday();
        yesterday.setDate("12");yesterday.setHigh("1123");yesterday.setLow("1");yesterday.setFl("1");yesterday.setFx("1");yesterday.setType("1");
        Forecast forecast = new Forecast();
        forecast.setDate("123");forecast.setHigh("1");forecast.setLow("1");forecast.setFengli("1");forecast.setFengxiang("1");forecast.setType("1");
        Forecast forecast1 = new Forecast();
        forecast1.setDate("1");forecast1.setHigh("1");forecast1.setLow("1");forecast1.setFengli("1");forecast1.setFengxiang("1");forecast1.setType("1");
        Forecast forecast2 = new Forecast();
        forecast2.setDate("1");forecast2.setHigh("1");forecast2.setLow("1");forecast2.setFengli("1");forecast2.setFengxiang("1");forecast2.setType("1");
        Forecast forecast3 = new Forecast();
        forecast3.setDate("12234");forecast3.setHigh("1123");forecast3.setLow("1");forecast3.setFengli("1");forecast3.setFengxiang("1");forecast3.setType("1");
        Forecast forecast4 = new Forecast();
        forecast4.setDate("1432");forecast4.setHigh("1123");forecast4.setLow("1");forecast4.setFengli("1");forecast4.setFengxiang("1");forecast4.setType("1");
        List<Forecast> forecastList = new ArrayList<Forecast>();
        forecastList.add(forecast);forecastList.add(forecast1);forecastList.add(forecast2);forecastList.add(forecast3);forecastList.add(forecast4);
        Weather weather = new Weather();
        weather.setCity("1");weather.setGanmao("1");weather.setYesterday(yesterday);weather.setWendu("1");weather.setForecast(forecastList);
        WeatherResponse weatherResponse = new WeatherResponse();
        weatherResponse.setData(weather);weatherResponse.setDesc("1");weatherResponse.setStatus(0);
        return weatherResponse;
    }
}
